from typing import List, Dict
import os
import sys
from jinja2 import Template
import subprocess
import shutil

from .Util import Util
from ..entity import AtomService, Message


class DDSClientUtil:

    @staticmethod
    def compileIdl(atom_service: AtomService):
        atom_service_name = atom_service._base_info.get_name()
        file_dir = f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/atomic_service/{atom_service_name}/idl/"
        Util.compileCmakeProject(
            file_dir,
            atom_service_name,
            file_type="idl",
        )

    @staticmethod
    def generateDDSCMakeLists(filename: str, idl_list: List[str]):
        filename = filename.split(".")[0]
        dds_src_path = f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/dds/"
        # 判断是否存在文件和目录
        if not os.path.exists(dds_src_path + filename):
            print(f"目录 {dds_src_path +filename} 不存在")
            return
        if not os.path.exists(os.path.join(dds_src_path, filename, filename + ".cpp")):
            print(
                f"文件 {os.path.join(dds_src_path, filename, filename + '.cpp')} 不存在"
            )
            return
        for idl in idl_list:
            if not os.path.exists(
                os.path.join(dds_src_path, "../idl/", idl, idl + ".idl")
            ):
                print(
                    f"idl {os.path.join(dds_src_path, '../idl/', idl + '.idl')} 不存在"
                )
                return

        # 生成CMakeLists.txt
        idl_template = Template(
            open(
                f"{os.path.dirname(os.path.abspath(__file__))}/../../templates/dds_process_template/dds_src_compile_cmake_template.j2"
            ).read()
        )
        res_str = idl_template.render(project_name=filename, idl_list=idl_list)

        # 确保目录存在
        os.makedirs(
            f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/dds/{filename}/",
            exist_ok=True,
        )

        # 将res_str写入框架内的cpp文件中，同名不同路径
        with open(
            f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/dds/{filename}/CMakeLists.txt",
            "w",
        ) as file:
            file.write(res_str)
        print(
            f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/dds/{filename}/CMakeLists.txt generated successfully!"
        )

    @staticmethod
    def compileDDS(filename: str):
        filename = filename.split(".")[0]
        file_dir = (
            f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/dds/{filename}/"
        )
        Util.compileCmakeProject(
            file_dir,
            filename,
            file_type="cpp",
        )
